package com.wondersgroup.fjzlpt.yyzyzx.service.impl.yyzygl;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.quick.framework.boot.web.wapper.QuickPrincipal;
import com.quick.framework.util.ExcelOrWordUtils;
import com.wondersgroup.fjzlpt.yyzyzx.dao.inter.yyzycx.CwxxDAO;
import com.wondersgroup.fjzlpt.yyzyzx.service.inter.yyzygl.CwyyglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

/**
 * 床位预约管理
 * @author gzb   
 * 2017年8月15日
 */
@Service
public class CwyyglServiceImpl implements CwyyglService {

	@Autowired
    private CwxxDAO cwxxDAO;

	/**
	 * 分页查询床位预约管理
	 * @param map
	 * @return
	 */
	public JSONObject queryPage(Map map){
//		return cwxxDAO.queryPage(map);
		return cwxxDAO.pageQueryCwxxAll(map);
	}

	@Override
	public JSONObject save(Map map) {
		JSONObject result = new JSONObject();
		//ZT设置
		Object ZT = map.get("ZT");
		if(ZT == null || "".equals(ZT) ){
			map.put("ZT", "1");
		}
		map.put("CWSYL",map.get("CWSYL")+"%");//床位使用率

		String type = map.get("type").toString();
		if("add".equals(type)){
			insert(map, result);
		}else{
			update(map, result);
		}
		return result;
	}

	/**
	 * 添加床位设置
	 * @param map
	 * @param result
	 */
	private void insert(Map map, JSONObject result){
		try {
			String CWXXBH = UUID.randomUUID().toString();
			map.put("CWXXBH", CWXXBH);

			//插入床位预约管理数据
			cwxxDAO.insert(map);

			result.put("state", "1");
			result.put("info", "床位预约管理数据保存成功！");
		} catch (Exception e) {
			result.put("info", "床位预约管理数据保存失败！");
			throw new RuntimeException("床位预约管理数据保存失败！");
		}
	}

	/**
	 * 修改床位设置
	 * @param map
	 * @param result
	 */
	private void update(Map map, JSONObject result){
		try {

			//更新床位预约管理数据
			cwxxDAO.updateForPrimaryKey(map);

			result.put("state", "1");
			result.put("info", "床位预约管理数据修改成功！");
		} catch (Exception e) {
			result.put("info", "床位预约管理数据修改失败！");
			throw new RuntimeException("床位预约管理数据修改失败！");
		}
	}

	/**
	 * 导出数据到Excel文件
	 * @param map
	 * @param request
	 * @param response
	 */
	@Override
	public void downloadToExcel(Map map, HttpServletRequest request, HttpServletResponse response) {
		JSONArray downData = cwxxDAO.queryAllOnView(map);
		
		//表头
		StringBuffer titleStr = new StringBuffer();
		titleStr.append("{'YYJBMC':'医院等级','YLJGMC':'医疗机构名称','YJKSMC':'科室名称','BQMC':'病区名称','SJKFCWS':'实际开放床位数','DQKCS':'当前空床数',")
				.append("'DQKYYCWS':'当前可预约床位数','STNYJKCS':'3天内预计空床数','STNKYYCWS':'3天内可预约床位数','YZNYJKCS':'1周内预计空床数',")
				.append("'YZNKYYCWS':'1周内可预约床位数','DDCWS':'等待床位数'}");
		JSONObject title = JSONObject.parseObject(titleStr.toString());
		downData.add(0, title);
		
		//排列循序
		List<String> titelField = new ArrayList<>();
		titelField.add("YYJBMC");
		titelField.add("YLJGMC");
		titelField.add("KSMC");
		titelField.add("BQMC");
		titelField.add("SJKFCWS");
		titelField.add("DQKCS");
		titelField.add("DQKYYCWS");
		titelField.add("STNYJKCS");
		titelField.add("STNKYYCWS");
		titelField.add("YZNYJKCS");
		titelField.add("YZNKYYCWS");
		titelField.add("DDCWS");
		ExcelOrWordUtils.downLoadExcelFile(downData, titelField ,"床位预约管理列表",request, response);
	}

	/**
	 * 通过PTJGID查询一级科室信息
	 * @param map
	 * @return
	 */
	public JSONArray queryYjksByPtjgid(Map<String,String> map){
		return cwxxDAO.queryYjksByJgxx(map);
	}

	/**
	 * 查询病区信息列表
	 * @param map
	 * @return
	 */
	public JSONArray queryBqxxByPtjgid(Map<String,String> map){
		return cwxxDAO.queryBqxxByJgxx(map);
	}


	/**
	 * 下载床位预约管理Excel模板
	 * @param response
	 */
	public void downExcelModel(HttpServletRequest request, HttpServletResponse response){
		JSONArray downData = new JSONArray();

		//表头
		StringBuffer titleStr = new StringBuffer();
		titleStr.append("{'a':'科室名称','b':'病区名称','c':'实际开放床位数','d':'当前空床数','e':'已预约床位数',")
				.append("'f':'当前可预约床位数','g':'3天内预计空床数','h':'3天内可预约床位数','i':'1周内预计空床数',")
				.append("'j':'1周内可预约床位数','k':'等待床位数'}");
		JSONObject title = JSONObject.parseObject(titleStr.toString());
		downData.add(0, title);

		//排列循序
		List<String> titelField = new ArrayList<>();
		titelField.add("a");
		titelField.add("b");
		titelField.add("c");
		titelField.add("d");
		titelField.add("e");
		titelField.add("f");
		titelField.add("g");
		titelField.add("h");
		titelField.add("i");
		titelField.add("j");
		titelField.add("k");
		ExcelOrWordUtils.downLoadExcelFile(downData, titelField ,"床位预约管理模板",request, response);
	}

	/**
	 * 下载床位预约管理模板值域
	 * @param response
	 */
	public void downExcelModelZy(HttpServletRequest request, HttpServletResponse response){
		JSONArray downData = new JSONArray();

		//表头
		StringBuffer titleStr = new StringBuffer();
		titleStr.append("{'KSMC':'科室名称','BQMC':'病区名称'}");
		JSONObject title = JSONObject.parseObject(titleStr.toString());
		downData.add(0, title);

		//排列循序
		List<String> titelField = new ArrayList<>();
		titelField.add("KSMC");
		titelField.add("BQMC");
		cwxxDAO.downExcelModelZy(downData, titelField ,"床位预约管理模板-值域",request, response);
	}

	/**
	 * 解析上传的Excel数据
	 * @param request
	 * @return
	 */
	public String parseExcalData(MultipartFile file, HttpServletRequest request){
		//return cwxxDAO.parseExcalData(file, request);
		String[] title = new String[] { "科室名称", "病区名称", "实际开放床位数","当前空床数","已预约床位数","当前可预约床位数",
				"3天内预计空床数", "3天内可预约床位数", "1周内预计空床数", "1周内可预约床位数", "等待床位数"};
		String[] titleField = new String[] { "YJKSDM", "BQDM", "SJKFCWS","DQKCS","YYYCWS","DQKYYCWS",
				"STNYJKCS", "STNKYYCWS", "YZNYJKCS", "YZNKYYCWS", "DDCWS"};

		JSONObject result = new JSONObject();
		try {
			result = ExcelOrWordUtils.parseExcalData(file.getInputStream(), title, titleField);
			if(result.getBoolean("state")){
				QuickPrincipal principal = (QuickPrincipal)request.getUserPrincipal();
				JSONObject userInfo = principal.getUserInfo();
				//数据格式化
				JSONObject otherData = this.packUserInfoToExcel(userInfo);
				JSONArray excelData = result.getJSONArray("data");
				for(int i = 0;i<excelData.size();i++){
					JSONObject item = excelData.getJSONObject(i);
					item.putAll(otherData);
				}
			}
		}catch (Exception e){
			throw new RuntimeException("解析Excel失败");
		}
		return result.toString();
	}

	/**
	 * 整合userInfo数据到excel数据
	 * @param userInfo
	 * @return
	 */
	private JSONObject packUserInfoToExcel(JSONObject userInfo){
		JSONObject result = new JSONObject();
		result.put("XZQHDM",userInfo.getString("JGXZQHDM"));
		String XZQHMC = cwxxDAO.queryXzqhmcByXzqhdm(userInfo.getString("JGXZQHDM"));
		result.put("XZQHMC",XZQHMC);
		result.put("YYDJDM",userInfo.getString("YYDJDM"));
		result.put("YYDJMC",userInfo.getString("YYDJMC"));
		result.put("YLJGDM",userInfo.getString("YLJGDM"));
		result.put("YLJGMC",userInfo.getString("YLJGMC"));
		result.put("ZT","1");
		return result;
	}

	/**
	 * 保存Excel数据
	 * @param map
	 * @return
	 */
	public JSONObject saveBatch(Map map){
		JSONObject result = new JSONObject();
		try {
			Object rows = map.get("rows");
			if(rows != null){
				JSONArray data = JSONArray.parseArray(rows.toString());
				for(Object item : data){
					JSONObject itemJo = (JSONObject)item;
					itemJo.put("CWXXBH", UUID.randomUUID().toString());
				}
				cwxxDAO.insertBatch((List)data);
			}

			result.put("state", "1");
			result.put("info", "导入成功！");
		} catch (Exception e) {
			result.put("info", "导入失败！");
			throw new RuntimeException("床位预约管理数据导入失败！");
		}
		return result;
	}

	/**
	 * 查询一级科室和病区（导入页面）
	 * @param map
	 * @return
	 */
	public JSONObject queryKsAndBq(Map<String,String> map){
		JSONObject result = new JSONObject();
		try{
			result.put("YJKSXX", cwxxDAO.queryYjksByJgxx(map));
			result.put("BQXX", cwxxDAO.queryBqxxByJgxx(map));
			result.put("state",true);
		}catch (Exception e){
			result.put("info","查询科室和病区失败!");
			throw new RuntimeException("查询科室和病区失败!");
		}
		return result;
	}


}
